package com.lianke.app.phpsharer.infomation;

import java.io.File;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.TextView;
import android.widget.Toast;

import com.lianke.app.phpsharer.AppApplication;
import com.lianke.app.phpsharer.AppApplicationApi;
import com.lianke.app.phpsharer.R;
import com.lianke.app.phpsharer.cache.ConfigCache;
import com.lianke.app.phpsharer.model.StatusInfo;
import com.tianxia.lib.baseworld.BaseApplication;
import com.tianxia.lib.baseworld.activity.AdapterActivity;
import com.tianxia.lib.baseworld.sync.http.AsyncHttpClient;
import com.tianxia.lib.baseworld.sync.http.AsyncHttpResponseHandler;
import com.tianxia.lib.baseworld.upgrade.AppUpgradeService;
import com.tianxia.lib.baseworld.utils.DownloadUtils;
import com.tianxia.lib.baseworld.utils.FileUtils;
import com.tianxia.lib.baseworld.utils.StringUtils;
import com.tianxia.lib.baseworld.widget.RefreshListView;
import com.tianxia.lib.baseworld.widget.RefreshListView.RefreshListener;
import com.tianxia.widget.image.SmartImageView;

public class InfomationTabActivity extends AdapterActivity<StatusInfo>
		implements RefreshListener {

	private SmartImageView mItemAvatar;
	private TextView mItemName;
	private TextView mItemDate;
	private TextView mItemText;
	private TextView item_fromText;

	private SimpleDateFormat mSinaWeiboDateFormat = new SimpleDateFormat(
			"EEE MMM dd HH:mm:ss Z yyyy", new DateFormatSymbols(Locale.US));
	private SimpleDateFormat mSimpleDateFormat;

	private int mLatestVersionCode = 0;
	private String mLatestVersionUpdate = null;
	private String mLatestVersionDownload = null;

	private int pageIndex = 0;
	private int start = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//设置加载数据
		setInfomationList();
		mSimpleDateFormat = new SimpleDateFormat("MM-dd HH:mm");
		listView.setOnCreateContextMenuListener(this);
	}

	/**
	 * 设置数据
	 */
	private void setInfomationList() {
		//////System.out.println(AppApplicationApi.INFOMATION_URL);
		// 获取缓存文件
		String cacheConfigString = ConfigCache.getUrlCache(AppApplicationApi.INFOMATION_URL);
		// 存在缓存文件的话
		if (cacheConfigString != null) {
			//System.out.println("读取缓存文件");
			showInfomationList(cacheConfigString);
			// 检查版本
			checkNewVersion();
		} else {
			//System.out.println("重新加载数据");
			AsyncHttpClient client = new AsyncHttpClient();
			//System.out.println(AppApplicationApi.INFOMATION_URL);
			client.get(AppApplicationApi.INFOMATION_URL,
					new AsyncHttpResponseHandler() {

						@Override
						public void onStart() { 
							////System.out.println("onStart");
						}

						@Override
						public void onSuccess(String result) {
							//System.out.println("onSuccess");
							ConfigCache.setUrlCache(result,AppApplicationApi.INFOMATION_URL);
							showInfomationList(result);
							//检查版本
							checkNewVersion();
						}

						@Override
						public void onFailure(Throwable arg0) {
							////System.out.println("onFailure");
							listView.setAdapter(null);
							showFailEmptyView();
						}

					});
		}
	}

	/**
	 * 根据返回的json数据显示信息到页面
	 * @param result
	 */
	private void showInfomationList(String result) {
		try {
			JSONObject statusConfig = new JSONObject(result);
			//最新版本
			mLatestVersionCode = statusConfig.optInt("version-code");
			//版本信息
			mLatestVersionUpdate = statusConfig.optString("version-update");
			//新app的下载地址
			mLatestVersionDownload = AppApplication.mDomain	+ statusConfig.optString("version-download");
			if (mLatestVersionDownload != null) {
				AppApplication.mApkDownloadUrl = mLatestVersionDownload;
			}
			//读取数据
			JSONArray statusList = statusConfig.getJSONArray("statuses");
			StatusInfo statusInfo = null;
			//for (int i = statusList.length() - 1; i >= 0; i--) {
			for (int i = 0; i <= statusList.length() -1; i++) {
				statusInfo = new StatusInfo();
				statusInfo.created = statusList.getJSONObject(i).optString("created_at");
				statusInfo.avatar = statusList.getJSONObject(i).getString("avatar");
				statusInfo.name = statusList.getJSONObject(i).getString("name");
				statusInfo.author = statusList.getJSONObject(i).getString("author");
				statusInfo.text = statusList.getJSONObject(i).getString("text");
				statusInfo.id = statusList.getJSONObject(i).getLong("id");
				//statusInfo.text_all = statusList.getJSONObject(i).getString("text_all");
				listData.add(statusInfo);
			}

			////System.out.println("pageindex的值->"+pageIndex);
			if (pageIndex == 0) {
				adapter = new Adapter(InfomationTabActivity.this);
				listView.setAdapter(adapter);
			} else {
				adapter.notifyDataSetChanged();
			}
			
			/*
			 * 发现个问题, 如果数据只有一条的话会显示下拉的信息,不知道什么原因
			 * */
			
			
			//获取页数
			pageIndex = statusConfig.getInt("page");
			////System.out.println("pageindex2的值->"+pageIndex);
			
			//为了更多的开始页数
			start = statusConfig.getInt("start"); 
			
			if (pageIndex == 1) {
				// if pageIndex == 1 means the page is the last page
				// so do not need show More FooterView any more
				((RefreshListView) listView).removeFootView();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/* (non-Javadoc)下拉刷新
	 * @see com.tianxia.lib.baseworld.widget.RefreshListView.RefreshListener#refreshing()
	 */
	public Object refreshing() {
		////System.out.println("refreshing-->");
		String result = null;
		if (AppApplication.mSdcardDataDir == null) {
			AppApplication.mSdcardDataDir = Environment
					.getExternalStorageDirectory().getPath()
					+ "/phpsharer/config/";
		}
		File file = new File(
				AppApplication.mSdcardDataDir
						+ "/"
						+ StringUtils
								.replaceUrlWithPlus(AppApplicationApi.INFOMATION_URL));
		if (file.exists() && file.isFile()) {
			file.delete();
		}
		try {
			DownloadUtils.download(AppApplicationApi.INFOMATION_URL, file,
					false, null);
			result = FileUtils.readTextFile(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/* (non-Javadoc)下来刷新结束
	 * @see com.tianxia.lib.baseworld.widget.RefreshListView.RefreshListener#refreshed(java.lang.Object)
	 */
	public void refreshed(Object obj) {
		////System.out.println("refreshed-->");
		if (obj != null) {
			listData.clear();
			pageIndex = 0;
			((RefreshListView) listView).addFootView();
			showInfomationList((String) obj);
		}

	}

	/* (non-Javadoc) 点击more
	 * @see com.tianxia.lib.baseworld.widget.RefreshListView.RefreshListener#more()
	 */
	public void more() {
		// TODO Auto-generated method stub
		//System.out.println("more");
		//System.out.println("pageIndex剩余" + pageIndex);
		if (pageIndex > 1) {
			//加载更多
			moreInfomationList(pageIndex - 1, start);
			start += 10;
		} else {
			Toast.makeText(this, "加载完毕", Toast.LENGTH_SHORT).show();
			((RefreshListView) listView).removeFootView();
		}
	}

	/**
	 * 加载更多
	 * @param pageIndex
	 */
	private void moreInfomationList(final int pageIndex, final int start) {
		//System.out.println(AppApplicationApi.INFOMATION_PAGE_URL + "?start=" + start);
		String cacheConfigString = ConfigCache.getUrlCache(AppApplicationApi.INFOMATION_PAGE_URL + start);
		if (cacheConfigString != null) {
			//System.out.println("cacheConfigString->null");
			showInfomationList(cacheConfigString);
		} else {
			//System.out.println("AsyncHttpClient");
			AsyncHttpClient client = new AsyncHttpClient();
			client.get(AppApplicationApi.INFOMATION_PAGE_URL + "?start=" + start, new AsyncHttpResponseHandler() {

				@Override
				public void onSuccess(String result) {
					////System.out.println(result);
					//ConfigCache.setUrlCache(result, AppApplicationApi.INFOMATION_PAGE_URL + start);
					showInfomationList(result);
					((RefreshListView) listView).finishFootView();
				}

				@Override
				public void onFailure(Throwable arg0) {
					((RefreshListView) listView).finishFootView();
					Toast.makeText(InfomationTabActivity.this,
							R.string.app_loading_fail, Toast.LENGTH_SHORT)
							.show();
					arg0.printStackTrace();
				}

			});
		}
	}

	@Override
	protected void setLayoutView() {
		// TODO Auto-generated method stub
		setContentView(R.layout.infomation_tab_activity);
		setListView(R.id.infomation_tab_list);
		((RefreshListView) listView).setOnRefreshListener(this);
		// 加载提示
		showLoadingEmptyView();
	}

	/*
	 * (non-Javadoc)获取页面布局
	 * 
	 * @see com.tianxia.lib.baseworld.activity.AdapterActivity#getView(int,
	 * android.view.View)
	 */
	@Override
	protected View getView(int position, View convertView) {
		View view = convertView;
		if (view == null) {
			view = LayoutInflater.from(getApplicationContext()).inflate(
					R.layout.infomation_tab_list_item, null);
		}

		mItemAvatar = (SmartImageView) view.findViewById(R.id.item_avatar);
		////System.out.println("listData.get(position).avatar->"+listData.get(position).avatar);
		mItemAvatar.setImageUrl(listData.get(position).avatar, R.drawable.icon,0);

		//标题
		mItemName = (TextView) view.findViewById(R.id.item_name);
		mItemName.setText(listData.get(position).name);
		mItemName.getPaint().setFakeBoldText(true);

		//mItemDate = (TextView) view.findViewById(R.id.item_date);
		//String dateString = listData.get(position).created;
		//mItemDate.setText(dateString);
		////System.out.println("dateString->"+dateString);
		/*
		if (dateString != null && !"".equals(dateString)) {
			try {
				Date date = mSinaWeiboDateFormat.parse(dateString);
				int second = (int) (System.currentTimeMillis() - date.getTime()) / 1000;
				if (second > 3600 && second <= 86400) {
					mItemDate.setText(second / 3600 + "小时前");
				} else if (second > 59 && second <= 3600) {
					mItemDate.setText(second / 60 + "分钟前");
				} else if (second <= 59) {
					mItemDate.setText(second + "秒前");
				} else {
					mItemDate.setText(mSimpleDateFormat.format(date));
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else {
			mItemDate.setText("");
		}
		*/
		
		
		//截取的100字的内容
		mItemText = (TextView) view.findViewById(R.id.item_text);
		mItemText.setText(listData.get(position).text);
		
		//全部的内容
		
		//发布时间
		String dateString = listData.get(position).created;
		item_fromText = (TextView) view.findViewById(R.id.item_from);
		item_fromText.setText("发布时间: "+dateString);

		return view;
	}

	@Override
	protected void onItemClick(AdapterView<?> adapterView, View view,
			int position, long id) {
		// TODO Auto-generated method stub
		//Intent intent = new Intent(this, CategoryListActivity.class);
		//Toast.makeText(this, "ID:" + listData.get(position).id, Toast.LENGTH_SHORT).show();
	}
	
	/* (non-Javadoc) 长按不松
     * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
     */
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        /*menu.setHeaderTitle(getString(R.string.info_options));
        //分享
        menu.add(0, 1, 1, getString(R.string.info_options_share));*/
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        /*switch (item.getItemId()) {
            case 1:
                //get item position
                ContextMenuInfo info = item.getMenuInfo();
                AdapterView.AdapterContextMenuInfo contextMenuInfo = (AdapterContextMenuInfo) info;
                int position = contextMenuInfo.position - 1;
                Intent intent=new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.info_options_share_title));
                intent.putExtra(Intent.EXTRA_TEXT, listData.get(position).text);
                startActivity(Intent.createChooser(intent, getString(R.string.setting_share_app_title)));
                break;
            default:
                break;
        }*/
        return super.onContextItemSelected(item);
    }
	
	@Override
    public void onBackPressed() {
        ((BaseApplication)getApplication()).exitApp(getParent());
    }
	
	public void checkNewVersion() {
		if (BaseApplication.mVersionCode < mLatestVersionCode
				&& BaseApplication.mShowUpdate) {
			new AlertDialog.Builder(this)
					.setTitle(R.string.check_new_version)
					.setMessage(mLatestVersionUpdate)
					.setPositiveButton(R.string.app_upgrade_confirm,
							new OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									////System.out.println("更新版本");
									Intent intent = new Intent(
											InfomationTabActivity.this,
											AppUpgradeService.class);
									intent.putExtra("downloadUrl",
											mLatestVersionDownload);
									startService(intent);
								}
							})
					.setNegativeButton(R.string.app_upgrade_cancel,
							new OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {

								}
							}).create().show();
			BaseApplication.mShowUpdate = false;
		}
	}

}
